package com.cls.system.controller;

import com.cls.common.annotation.ControllerEndpoint;
import com.cls.common.exception.MyException;
import com.cls.common.utils.FastDFSUtil;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.ResponseVO;
import com.cls.system.entity.SysFile;
import com.cls.system.service.ISysFileService;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 系统附件 Controller
 *
 * @author wmm
 * @date 2020-12-02 09:33:06
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class SysFileController extends BaseController {

    private final ISysFileService sysFileService;

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ControllerEndpoint(operation = "上传文件", exceptionMessage = "上传附件失败")
    @PostMapping("upload")
    @ResponseBody
    public ResponseVO upload(MultipartFile file) {
        SysFile sysFile = null;
        try {
            sysFile = sysFileService.uploadFile(file);
        } catch (IOException | org.csource.common.MyException e) {
            e.printStackTrace();
            throw new MyException("上传失败");
        }
        return ResponseVO.success(sysFile);
    }

    /**
     * 下载文件
     *
     * @param fileId
     * @return
     * @throws IOException
     */
    @ControllerEndpoint(operation = "下载文件", exceptionMessage = "下载文件失败")
    @GetMapping("download/{fileId}")
    @ResponseBody
    public void download(@PathVariable Long fileId, HttpServletResponse response){
        try {
            sysFileService.download(fileId, response);
        } catch (org.csource.common.MyException | IOException e) {
            e.printStackTrace();
            throw new MyException("下载文件失败");
        }
    }

    /**
     * 展示图片
     *
     * @param fileId
     * @return
     * @throws IOException
     */
    @ControllerEndpoint(operation = "下载文件", exceptionMessage = "下载文件失败")
    @GetMapping("detail/{fileId}")
    @ResponseBody
    public ResponseVO detail(@PathVariable Long fileId) {
        SysFile sysFile = sysFileService.getById(fileId);
        if (sysFile != null) {
            byte[] bytes = new byte[0];
            try {
                bytes = FastDFSUtil.fileDetail(sysFile.getUrl());
            } catch (Exception e) {
                e.printStackTrace();
                throw new MyException("下载文件失败");
            }
            return ResponseVO.success(bytes);
        }
        return ResponseVO.failure("文件不存在");
    }

}
